package com.wanpinghui.supplier.widgets;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.netease.nimlib.sdk.media.player.AudioPlayer;
import com.netease.nimlib.sdk.media.player.OnPlayListener;
import com.wanpinghui.supplier.MApplication;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.common.BaseActivity;
import com.wanpinghui.supplier.utils.FileUtil;
import com.wanpinghui.wphlibrary.model.db.manager.MsgDbManager;
import com.wanpinghui.wphlibrary.model.message.bean.MessagesExt;
import com.wanpinghui.wphlibrary.model.message.bean.MsgBean;
import com.yunshl.yunshllibrary.utils.TextUtil;

import java.io.File;

/**
 * Created by xiongning on 17-12-7.
 */

public class MsgLeftAudioView extends LinearLayout implements OnPlayListener {

    private TextView tv_voice_time;

    private RelativeLayout rl_msg_content;

    private View id_recoder_anim;

    private SpinView sv;

    private ImageView iv_error;

    private MsgBean msgBean;

    private int mMinItemWidth; //最小的item宽度

    private int mMaxItemWidth; //最大的item宽度

    private AudioPlayer audioPlayer;

    private int play_time = 0;

    private BroadcastReceiver mBroadcastReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (audioPlayer != null && audioPlayer.isPlaying())
                audioPlayer.stop();
            context.unregisterReceiver(mBroadcastReceiver);
        }
    };

    public MsgLeftAudioView(Context context) {
        super(context);
        init(context);
    }

    public MsgLeftAudioView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MsgLeftAudioView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public MsgLeftAudioView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    private void init(Context context) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View mView = inflater.inflate(R.layout.item_msg_left_voice, this);
        rl_msg_content = (RelativeLayout) mView.findViewById(R.id.rl_msg_content);
        tv_voice_time = (TextView) mView.findViewById(R.id.tv_voice_time);
        id_recoder_anim = (View) mView.findViewById(R.id.id_recoder_anim);
        sv = (SpinView) mView.findViewById(R.id.sv);
        iv_error = (ImageView) mView.findViewById(R.id.iv_error);
        initMaxOrMinLen(context);
        rl_msg_content.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                playAudioMsg();
            }
        });

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.wpsd.audio.stop");
        context.registerReceiver(mBroadcastReceiver,intentFilter);
    }

    private void play(String path) {
        try {
            if (audioPlayer == null) {
                audioPlayer = new AudioPlayer(getContext(), path, this);
            }
            audioPlayer.start(AudioManager.STREAM_MUSIC);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void playAudioMsg() {
        id_recoder_anim.setBackgroundResource(R.mipmap.message_icon_voice_left_3);
        MessagesExt ext = MessagesExt.getMessagesExt(msgBean.getExt());
        if (TextUtil.isNotEmpty(ext.getFile_path()) && new File(ext.getFile_path()).exists()) {
            play(ext.getFile_path());
        } else {
            FileUtil.downLoadFile(msgBean.getMsg(), new FileUtil.OnDownListener() {
                @Override
                public void onResult(String path, boolean isSuccess) {
                    if (isSuccess) {
                        MessagesExt ext = MessagesExt.getMessagesExt(msgBean.getExt());
                        ext.setFile_path(path);
                        MsgDbManager.getInstance().saveMsbBean(msgBean);
                        play(path);
                    } else {
                        ((BaseActivity) MApplication.getAContext().getTopActivity()).showWarningText("播放失败");
                    }
                }
            });
        }
    }


    private void initMaxOrMinLen(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        mMaxItemWidth = (int) (outMetrics.widthPixels * 0.7f);
        mMinItemWidth = (int) (outMetrics.widthPixels * 0.15f);
    }

    public void initData(MsgBean msgBean) {
        this.msgBean = msgBean;
        MessagesExt ext = MessagesExt.getMessagesExt(msgBean.getExt());
        setVoiceLen(ext.getFile_len());
        switch (msgBean.getSend_statu()) {
            case 0:
                setError(false);
                setSending(true);
                break;
            case 1:
                setError(false);
                setSending(false);
                break;
            case 2:
                setError(true);
                setSending(false);
                break;
        }
    }

    public void setVoiceLen(long voice_time) {
        int showTime = Math.round(voice_time / 1000.0f);
        tv_voice_time.setText(Math.round(showTime) + "\"");//(Math.round(getItem(position).time) + "\"");
        ViewGroup.LayoutParams lp = rl_msg_content.getLayoutParams();
        lp.width = (int) (mMinItemWidth + (mMaxItemWidth / 60f) * showTime);
    }

    public void setSending(boolean isSendding) {
        if (isSendding)
            sv.setVisibility(View.VISIBLE);
        else
            sv.setVisibility(View.GONE);

    }

    public void setError(boolean isError) {
        if (isError)
            iv_error.setVisibility(View.VISIBLE);
        else
            iv_error.setVisibility(View.GONE);
    }

    @Override
    public void onPrepared() {
        id_recoder_anim.setBackgroundResource(R.drawable.left_play_anim);
        AnimationDrawable animation = (AnimationDrawable) id_recoder_anim.getBackground();
        animation.start();
    }

    @Override
    public void onCompletion() {
        id_recoder_anim.setBackgroundResource(R.mipmap.message_icon_voice_left_3);
    }

    @Override
    public void onInterrupt() {
        id_recoder_anim.setBackgroundResource(R.mipmap.message_icon_voice_left_3);
    }

    @Override
    public void onError(String error) {
        id_recoder_anim.setBackgroundResource(R.mipmap.message_icon_voice_left_3);
    }

    @Override
    public void onPlaying(long curPosition) {

    }
}
